{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# **Deforum Colab Notebook (v0.9)**"
      ],
      "metadata": {
        "id": "R-F_f4vqFpne"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Setup"
      ],
      "metadata": {
        "id": "KVqY9lP9nst_"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@markdown **Environment Setup**\n",
        "import os\n",
        "import subprocess\n",
        "import sys\n",
        "import time\n",
        "\n",
        "def setup_environment():\n",
        "    # Check if in google colab\n",
        "    try:\n",
        "        ipy = get_ipython()\n",
        "        if 'google.colab' not in str(ipy):\n",
        "            print('Not running on Google Colab. Environment setup aborted.\\n')\n",
        "            print('```')\n",
        "            print('Environment: Non Google Colab')\n",
        "            print('Error: This notebook is not running in Google Colab.')\n",
        "            print('```')\n",
        "            print(\"Please ensure this notebook runs in Google Colab.\")\n",
        "            print(\"If this problem persists, please open an issue at: https://github.com/deforum-studio/deforum/issues\")\n",
        "            return\n",
        "    except Exception:\n",
        "        print(\"Error! Not running in an IPython environment. Environment setup aborted.\\n\")\n",
        "        print('```')\n",
        "        print('Environment: Non IPython')\n",
        "        print('Error: This notebook is not running in an IPython environment.')\n",
        "        print('```')\n",
        "        print(\"If this problem persists, please open an issue at: https://github.com/deforum-studio/deforum/issues\")\n",
        "        return\n",
        "\n",
        "    # Start the timer\n",
        "    start_time = time.time()\n",
        "\n",
        "    # Specify requirements in a list for easy editing\n",
        "    requirements = ['einops', 'timm', 'basicsr', 'accelerate', 'transformers', 'torchsde']\n",
        "\n",
        "    try:\n",
        "        # Clone the deforum repo\n",
        "        process = subprocess.Popen(['git', 'clone', 'https://github.com/deforum-studio/deforum.git'])\n",
        "        process.wait()\n",
        "\n",
        "        # Install required packages in one go\n",
        "        subprocess.check_call([sys.executable, '-m', 'pip', 'install', *requirements])\n",
        "\n",
        "        # Append the path\n",
        "        sys.path.append('./deforum/src/')\n",
        "    except Exception as e:\n",
        "        print(\"An error occurred during the setup.\\n\")\n",
        "        print('```')\n",
        "        print('Error:', str(e))\n",
        "        print('```')\n",
        "        print(\"Please copy the above text and open an issue at: https://github.com/deforum-studio/deforum/issues\")\n",
        "        return\n",
        "\n",
        "    # Report the total time\n",
        "    total_time = time.time() - start_time\n",
        "    print('Environment setup completed successfully. Total time: {:.2f} seconds'.format(total_time))\n",
        "\n",
        "setup_environment()\n",
        "\n",
        "# import deforum\n",
        "try:\n",
        "    from deforum import DeforumAnimationPipeline\n",
        "except Exception as e:\n",
        "    print(\"An error occurred during the import.\")\n",
        "    print('```')\n",
        "    print('Error:', str(e))\n",
        "    print('```')\n",
        "    print(\"Please copy the above text and open an issue at: https://github.com/deforum-studio/deforum/issues\")"
      ],
      "metadata": {
        "cellView": "form",
        "id": "f_8qrxSHJ7wu"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#@markdown **Path Setup**\n",
        "def path_setup():\n",
        "    # Start the timer\n",
        "    start_time = time.time()\n",
        "    try:\n",
        "        models_path = \"models\" #@param {type:\"string\"}\n",
        "        output_path = \"output\" #@param {type:\"string\"}\n",
        "        mount_google_drive = True #@param {type:\"boolean\"}\n",
        "        force_remount = False\n",
        "        models_path_gdrive = \"/content/drive/MyDrive/AI/models\" #@param {type:\"string\"}\n",
        "        output_path_gdrive = \"/content/drive/MyDrive/AI/output\" #@param {type:\"string\"}\n",
        "\n",
        "        print(\"Setting up paths...\")\n",
        "\n",
        "        try:\n",
        "            ipy = get_ipython()\n",
        "\n",
        "            if 'google.colab' in str(ipy):\n",
        "                print(\"Executing in Google Colab...\")\n",
        "\n",
        "                if mount_google_drive:\n",
        "                    print(\"Mounting Google Drive...\")\n",
        "\n",
        "                    from google.colab import drive # type: ignore\n",
        "                    try:\n",
        "                        drive_path = \"/content/drive\"\n",
        "                        drive.mount(drive_path,force_remount=force_remount)\n",
        "                        models_path = models_path_gdrive\n",
        "                        output_path = output_path_gdrive\n",
        "\n",
        "                        print(\"Mounted Google Drive successfully.\")\n",
        "                    except:\n",
        "                        print(\"Error mounting drive or with drive path variables.\")\n",
        "                        print(\"Reverting to default path variables.\")\n",
        "\n",
        "        except:\n",
        "            print(\"Executing in a local environment...\")\n",
        "            print(\"Using default path variables.\")\n",
        "\n",
        "    except Exception as e:\n",
        "        print(f\"An unexpected error occurred during the path setup: {str(e)}\")\n",
        "        print(\"If you encounter any issues, please copy this console output and open an issue at: https://github.com/deforum-studio/deforum/issues\")\n",
        "\n",
        "    finally:\n",
        "        print(f\"Models will be saved in this path: {models_path}\")\n",
        "        print(f\"Output will be saved in this path: {output_path}\")\n",
        "\n",
        "    # Report the total time\n",
        "    total_time = time.time() - start_time\n",
        "    print('Path setup completed successfully. Total time: {:.2f} seconds'.format(total_time))\n",
        "    return models_path, output_path\n",
        "\n",
        "models_path, output_path = path_setup()"
      ],
      "metadata": {
        "cellView": "form",
        "id": "ZlL6SD7qiDQh"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import os, re\n",
        "from urllib.parse import urlparse\n",
        "\n",
        "def get_civitai_model_id(civitai_url):\n",
        "    try:\n",
        "        model_id = re.search(r\"models/(\\d+)\", civitai_url).group(1)\n",
        "        if not model_id:\n",
        "            print(\"No Model ID found in the download links.\\n\")\n",
        "            return None\n",
        "\n",
        "        print(f\"Model ID successfully obtained: {model_id}\\n\")\n",
        "        return model_id\n",
        "\n",
        "    except Exception as e:\n",
        "        print(f\"An unexpected error occurred during the model setup: {str(e)}\\n\")\n",
        "        print(\"If you encounter any issues, please copy this console output and open an issue at: https://github.com/deforum-studio/deforum/issues\")\n",
        "\n",
        "\n",
        "def instantiate_deforum_pipeline(models_path):\n",
        "\n",
        "    # Start the timer\n",
        "    start_time = time.time()\n",
        "\n",
        "    model_map = {\n",
        "        \"SDXL-Base v1.0\": {\"url\": \"https://civitai.com/models/101055?modelVersionId=128078\"},\n",
        "        \"SDXL-ProtoVisonXL_0630\": {\"url\": \"https://civitai.com/models/125703?modelVersionId=201514\"},\n",
        "        \"SDXL-DynaVisionXL_0557\": {\"url\": \"https://civitai.com/models/122606?modelVersionId=198962\"},\n",
        "        \"SDXL-NightVisionXL_0770\": {\"url\": \"https://civitai.com/models/128607?modelVersionId=201643\"},\n",
        "        \"SDXL-ZavyChromaXL_v2.1\": {\"url\": \"https://civitai.com/models/119229?modelVersionId=169740\"},\n",
        "        \"SDXL-JuggernautXL_v6\": {\"url\": \"https://civitai.com/models/133005?modelVersionId=198530\"},\n",
        "        \"SDXL-UnstableDiffusers_YamerMix_v8\": {\"url\": \"https://civitai.com/models/84040?modelVersionId=196039\"},\n",
        "        \"SDXL-Copax_TimelessXL_v8\": {\"url\": \"https://civitai.com/models/118111?modelVersionId=198246\"},\n",
        "        \"SD_1.5-RealisticVision_v5.1\": {\"url\": \"https://civitai.com/models/4201?modelVersionId=130072\"},\n",
        "        \"SD_1.5-Dreamshaper_v8\": {\"url\": \"https://civitai.com/models/4384/dreamshaper?modelVersionId=128713\"},\n",
        "        \"SD_1.5-RevAnimated_v.1.2.2\": {\"url\": \"https://civitai.com/models/7371?modelVersionId=46846\"},\n",
        "        \"SD_1.5-GhostMix_v2\": {\"url\": \"https://civitai.com/models/36520?modelVersionId=76907\"}\n",
        "    }\n",
        "\n",
        "    try:\n",
        "        model_checkpoint =  \"SDXL-ProtoVisonXL_0630\" #@param ['(model_path_or_url)', 'SDXL-Base v1.0', 'SDXL-ProtoVisonXL_0630', 'SDXL-DynaVisionXL_0557', 'SDXL-NightVisionXL_0770', 'SDXL-ZavyChromaXL_v2.1', 'SDXL-JuggernautXL_v6', 'SDXL-UnstableDiffusers_YamerMix_v8', 'SDXL-Copax_TimelessXL_v8', 'SD_1.5-RealisticVision_v5.1', 'SD_1.5-Dreamshaper_v8', 'SD_1.5-RevAnimated_v.1.2.2', 'SD_1.5-GhostMix_v2']\n",
        "        model_path_or_url = '' #@param {type:\"string\"}\n",
        "\n",
        "        if model_checkpoint == \"(model_path_or_url)\":\n",
        "            if os.path.isfile(model_path_or_url):\n",
        "                print(\"Loading local model file.\\n\")\n",
        "                deforum = DeforumAnimationPipeline.from_single_file(model_path_or_url)\n",
        "            else:\n",
        "                parse_result = urlparse(model_path_or_url)\n",
        "                if parse_result.scheme and parse_result.netloc:\n",
        "                    print(\"Loading model from URL.\\n\")\n",
        "                    model_id = get_civitai_model_id(model_path_or_url)\n",
        "                    try:\n",
        "                        deforum = DeforumAnimationPipeline.from_civitai(modelid=str(model_id), cache_dir=models_path)\n",
        "                    except Exception as e:\n",
        "                        print(f\"Error loading model with from_civitai ({str(e)}), trying from_download_url.\\n\")\n",
        "                        deforum = DeforumAnimationPipeline.from_download_url(model_path_or_url, cache_dir=models_path)\n",
        "                else:\n",
        "                    print(f\"model_checkpoint: {model_checkpoint}\")\n",
        "                    print(f\"model_path_or_url: {model_path_or_url}\")\n",
        "                    print(\"The model_path_or_url you provided is neither a valid local file nor a URL.\\nPlease try again or select a model from the dropdown.\")\n",
        "                    print(\"If you believe this is an bug, please copy this console output and open an issue at: https://github.com/deforum-studio/deforum/issues\")\n",
        "        else:\n",
        "            model_path_or_url = model_map[model_checkpoint][\"url\"]\n",
        "            model_id = get_civitai_model_id(model_path_or_url)\n",
        "            try:\n",
        "                deforum = DeforumAnimationPipeline.from_civitai(modelid=str(model_id), cache_dir=models_path)\n",
        "            except Exception as e:\n",
        "                print(f\"Error loading model with from_civitai ({str(e)})\")\n",
        "\n",
        "    except Exception as e:\n",
        "        print(f\"An unexpected error occurred during the model setup: {str(e)}\")\n",
        "        print(\"If you encounter any issues, please copy this console output and open an issue at: https://github.com/deforum-studio/deforum/issues\")\n",
        "\n",
        "    # Report the total time\n",
        "    total_time = time.time() - start_time\n",
        "    print('Model setup completed successfully. Total time: {:.2f} seconds'.format(total_time))\n",
        "    return deforum\n",
        "\n",
        "deforum = instantiate_deforum_pipeline(models_path)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "YJRPHW01fafD"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Run"
      ],
      "metadata": {
        "id": "u6pjyseECqlg"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "data = {\"W\": 1024, \"H\": 1024}\n",
        "deforum(**data)"
      ],
      "metadata": {
        "id": "768kh3KXC_kT"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}